package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"recruit-pro/cache"
	"recruit-pro/model"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var Count int64
	model.DB.Model(&model.Bo{}).Count(&Count)
	var boos []model.Bo
	redis_key := "list_"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {

		model.DB.Offset(offset).Limit(size).Find(&boos)
		jsonData, _ := json.Marshal(boos)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &boos)
	}

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  boos,
		"count": Count,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var boss model.Bo
	redis_key := "detail"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {

		model.DB.Where("id=?", id).Find(&boss)
		jsonData, _ := json.Marshal(boss)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &boss)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": boss,
	})
}
func Count(c *gin.Context) {
	id := c.Query("id")
	var boss model.Bo
	boss.Count++
	redis_key := "shou_"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {

		model.DB.Where("id=?", id).Find(&boss)
		jsonData, _ := json.Marshal(boss)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &boss)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "收藏成功",
	})
}
